package com.atguigu.controller;

import com.atguigu.bean.UserInfo;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author mqx
 * @date 2020 年 7 月 20 日 0020 17:44:50
 */
@Controller
public class IndexController {

    @GetMapping("/index")
    public String index(){
        return "login";
    }

    @GetMapping("/findAll")
    @ResponseBody
    public String findAll(){
        return "findAll";
    }

    @GetMapping("/find")
    @ResponseBody
    public String find(){
        return "find";
    }

    @RequestMapping("/success")
    public String success(){
        return "success";
    }

    @PostMapping("/fail")
    public String fail(){
        return "fail";
    }

    // 没有访问权限
    @GetMapping("/unauth")
    public String accessDenyPage(){
        return "unauth";
    }

    // 测试注解：
    @RequestMapping("testSecured")
    @ResponseBody
    @Secured({"ROLE_normal","ROLE_管理员"})
    public String helloUser() {
        return "hello,user";
    }

    @RequestMapping("/testPostAuthorize")
    @ResponseBody
    @PostAuthorize("hasAnyAuthority('menu:system')")
    public String preAuthorize(){
        System.out.println("test--PostAuthorize");
        return "PostAuthorize";
    }

    @RequestMapping("getAll")
    @PreAuthorize("hasRole('ROLE_管理员')")
    @PostFilter("filterObject.username == 'admin1'")
    @ResponseBody
    public List<UserInfo> getAllUser(){

        ArrayList<UserInfo> list = new ArrayList<>();
        list.add(new UserInfo(1l,"admin1","6666"));
        list.add(new UserInfo(2l,"admin2","888"));
        return list;
    }

    @RequestMapping("getTestPreFilter")
    @PreAuthorize("hasRole('ROLE_管理员')")
    @PreFilter(value = "filterObject.id%2==0")
    @ResponseBody
    public List<UserInfo> getTestPreFilter(@RequestBody List<UserInfo> list){
        list.forEach(t-> {
            System.out.println(t.getId()+"\t"+t.getUsername());
        });
        return list;
    }

}
